package com.dobest.securitydemo.filter;

import com.alibaba.fastjson.JSON;
import com.dobest.securitydemo.common.Result;
import com.dobest.securitydemo.common.TokenUtils;
import com.dobest.securitydemo.model.vo.UserDetail;
import com.dobest.securitydemo.service.IUserService;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.util.JSONPObject;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Copyright © 2018胡建松. All rights reserved.
 *
 * @Package: com.dobest.securitydemo
 * @author: Jounghu
 * @date: 2018/7/17 22:16
 * @version: V1.0
 */
@Slf4j
public class OauthFilter extends UsernamePasswordAuthenticationFilter {

    private static final String AUTH_HEADER = "bear ";
    private static final String CONTENT_TYPE = "application/json";


    @Autowired
    ModelMapper modelMapper;

    @Autowired
    TokenUtils tokenUtils;

    @Autowired
    IUserService userService;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        log.info("OauthFilter 开始鉴权...");
        // 获取token
        HttpServletRequest request = (HttpServletRequest) req;
        String header = request.getHeader(AUTH_HEADER);
        if (header == null) {
            return;
        }
        String username = tokenUtils.getUsernameFromToken(header);

        if (StringUtils.isEmpty(username)) {
            return;
        }

        //load username
        UserDetail userDetail = userService.findUserDetailByUserName(username);
        if (userDetail == null) {
            // 用户篡改了token
            return;
        }

        if (tokenUtils.validateToken(header, userDetail)) {
            //验证通过，设置相对应的权限
            UsernamePasswordAuthenticationToken upAuthToken = new UsernamePasswordAuthenticationToken(userDetail, null, userDetail.getAuthorities());
            upAuthToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            // 将权限写入本次会话
            SecurityContextHolder.getContext().setAuthentication(upAuthToken);
        }
        if(!userDetail.isEnabled()){
            Result result = new Result();
            result.setCode(400);
            result.setMsg("你被关小黑屋了、、");
            res.setContentType(CONTENT_TYPE);
            res.getWriter().write(JSON.toJSONString(result));
        }
        chain.doFilter(req, res);
    }

}
